<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete, Edit, Plus, Refresh, Search } from '@element-plus/icons-vue'
import { getParkingSpaceController, getOwnerController } from '@/api-client'
import type {
  ParkingSpaceQueryRequest,
  ParkingSpaceSaveRequest,
  ParkingSpaceVO,
} from '@/api-client'

interface ParkingSpaceFormModel {
  id?: number
  numbers: string
  status: number
  ownerId?: number
  description?: string
}

interface OwnerOption {
  id: number
  name: string
  tel?: string
  houseLabel?: string
}

const parkingApi = getParkingSpaceController()
const ownerApi = getOwnerController()

const loading = ref(false)
const submitLoading = ref(false)
const tableData = ref<ParkingSpaceVO[]>([])
const total = ref(0)
const selectedRows = ref<ParkingSpaceVO[]>([])

const ownerOptions = ref<OwnerOption[]>([])
const ownerLoading = ref(false)

const pagination = reactive({
  current: 1,
  pageSize: 10,
})

const searchForm = reactive<ParkingSpaceQueryRequest>({
  current: 1,
  pageSize: 10,
  numbers: '',
  status: undefined,
  ownerName: '',
})

const createEmptyForm = (): ParkingSpaceFormModel => ({
  id: undefined,
  numbers: '',
  status: 0,
  ownerId: undefined,
  description: '',
})

const parkingForm = reactive<ParkingSpaceFormModel>(createEmptyForm())
const formRef = ref<FormInstance>()
const dialogVisible = ref(false)
const isEdit = ref(false)

const statusOptions = [
  { label: '空闲', value: 0, type: 'success' },
  { label: '已占用', value: 1, type: 'danger' },
]

const rules = reactive<FormRules<ParkingSpaceFormModel>>({
  numbers: [{ required: true, message: '请输入车位编号', trigger: 'blur' }],
  status: [{ required: true, message: '请选择车位状态', trigger: 'change' }],
})

const fetchParkingList = async () => {
  loading.value = true
  try {
    const response = await parkingApi.search2({
      ...searchForm,
      current: pagination.current,
      pageSize: pagination.pageSize,
    })
    if (response.code === 200 && response.data) {
      tableData.value = response.data.records || []
      total.value = response.data.total || 0
    } else {
      ElMessage.error(response.message || '获取车位列表失败')
    }
  } catch (error) {
    console.error('fetchParkingList error:', error)
    ElMessage.error('获取车位列表失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.current = 1
  searchForm.current = 1
  fetchParkingList()
}

const handleReset = () => {
  searchForm.numbers = ''
  searchForm.status = undefined
  searchForm.ownerName = ''
  handleSearch()
}

const handleSelectionChange = (rows: ParkingSpaceVO[]) => {
  selectedRows.value = rows
}

const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.current = 1
  fetchParkingList()
}

const handleCurrentChange = (page: number) => {
  pagination.current = page
  fetchParkingList()
}

const resetForm = () => {
  Object.assign(parkingForm, createEmptyForm())
  formRef.value?.clearValidate()
}

const openDialog = () => {
  dialogVisible.value = true
}

const closeDialog = () => {
  dialogVisible.value = false
  submitLoading.value = false
}

const ensureOwnerOption = (owner?: ParkingSpaceVO['owner']) => {
  if (!owner?.id) return
  const exists = ownerOptions.value.some((item) => item.id === owner.id)
  if (!exists) {
    ownerOptions.value.push({
      id: owner.id,
      name: owner.name || '未命名业主',
      tel: owner.tel || undefined,
    })
  }
}

const fetchOwnerOptions = async (keyword = '') => {
  ownerLoading.value = true
  try {
    const response = await ownerApi.listOwner({
      current: 1,
      pageSize: 20,
      userName: keyword || undefined,
    })
    if (response.code === 200 && response.data) {
      ownerOptions.value = (response.data.records || []).map<OwnerOption>((item) => ({
        id: item.id!,
        name: item.userName || '未命名业主',
        tel: item.tel || undefined,
        houseLabel: item.houseVO
          ? `${item.houseVO.building?.numbers || ''} ${item.houseVO.numbers || ''}`
          : undefined,
      }))
    }
  } catch (error) {
    console.error('fetchOwnerOptions error:', error)
  } finally {
    ownerLoading.value = false
  }
}

const handleAdd = () => {
  isEdit.value = false
  resetForm()
  openDialog()
}

const handleEdit = (row: ParkingSpaceVO) => {
  isEdit.value = true
  resetForm()
  parkingForm.id = row.id
  parkingForm.numbers = row.numbers || ''
  parkingForm.status = row.status ?? 0
  parkingForm.ownerId = row.ownerId
  parkingForm.description = row.description || ''
  if (row.owner) {
    ensureOwnerOption(row.owner)
  }
  openDialog()
}

const submitForm = async (form: FormInstance | undefined) => {
  if (!form) return
  await form.validate(async (valid) => {
    if (!valid) return
    const payload: ParkingSpaceSaveRequest = {
      numbers: parkingForm.numbers,
      status: parkingForm.status,
      ownerId: parkingForm.ownerId,
      description: parkingForm.description,
    }
    submitLoading.value = true
    try {
      if (isEdit.value && parkingForm.id) {
        await parkingApi.update4(parkingForm.id, payload)
        ElMessage.success('更新成功')
      } else {
        await parkingApi.add4(payload)
        ElMessage.success('新增成功')
      }
      closeDialog()
      fetchParkingList()
    } catch (error) {
      console.error('submitForm error:', error)
      ElMessage.error(isEdit.value ? '更新失败，请稍后重试' : '新增失败，请稍后重试')
    } finally {
      submitLoading.value = false
    }
  })
}

const handleDelete = async (row: ParkingSpaceVO) => {
  if (!row.id) return
  try {
    await ElMessageBox.confirm(`确认删除车位「${row.numbers || ''}」吗？`, '提示', {
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
    })
    loading.value = true
    await parkingApi.delete4({ id: row.id })
    ElMessage.success('删除成功')
    fetchParkingList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('handleDelete error:', error)
      ElMessage.error('删除失败，请稍后重试')
    }
  } finally {
    loading.value = false
  }
}

const handleBatchDelete = async () => {
  const ids = selectedRows.value
    .map((item) => item.id)
    .filter((id): id is number => id !== undefined)
  if (ids.length === 0) {
    ElMessage.warning('请选择要删除的车位')
    return
  }
  try {
    await ElMessageBox.confirm(`确认批量删除选中的 ${ids.length} 个车位吗？`, '提示', {
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
    })
    loading.value = true
    await parkingApi.deleteBatch2(ids)
    ElMessage.success('批量删除成功')
    fetchParkingList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('handleBatchDelete error:', error)
      ElMessage.error('批量删除失败，请稍后重试')
    }
  } finally {
    loading.value = false
  }
}

const remoteSearchOwner = (keyword: string) => {
  fetchOwnerOptions(keyword)
}

const ownerLabel = (option: OwnerOption) => {
  const parts = [option.name]
  if (option.houseLabel) parts.push(option.houseLabel)
  if (option.tel) parts.push(option.tel)
  return parts.join(' / ')
}

onMounted(() => {
  fetchParkingList()
  fetchOwnerOptions()
})
</script>

<template>
  <div class="parking-view">
    <div class="page-header">
      <div>
        <h2>车位管理</h2>
        <p>维护停车位基础信息，支持快速登记使用情况与关联业主。</p>
      </div>
    </div>

    <div class="search-section">
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="车位编号">
          <el-input
            v-model="searchForm.numbers"
            placeholder="请输入车位编号"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="车位状态">
          <el-select v-model="searchForm.status" placeholder="请选择" clearable style="width: 160px">
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="业主姓名">
          <el-input
            v-model="searchForm.ownerName"
            placeholder="请输入业主姓名"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch"> 搜索 </el-button>
          <el-button :icon="Refresh" @click="handleReset"> 重置 </el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="action-section">
      <el-button type="primary" :icon="Plus" @click="handleAdd"> 新增车位 </el-button>
      <el-button
        type="danger"
        :icon="Delete"
        :disabled="selectedRows.length === 0"
        @click="handleBatchDelete"
      >
        批量删除
      </el-button>
    </div>

    <div class="table-section">
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        stripe
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="numbers" label="车位编号" min-width="140" />
        <el-table-column label="使用状态" width="120">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'danger' : 'success'">
              {{ row.status === 1 ? '已占用' : '空闲' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="关联业主" min-width="200">
          <template #default="{ row }">
            <div>{{ row.owner?.name || '-' }}</div>
            <div class="cell-sub" v-if="row.owner?.tel">{{ row.owner.tel }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="备注" min-width="220" show-overflow-tooltip />
        <el-table-column label="操作" fixed="right" width="180">
          <template #default="{ row }">
            <el-button type="primary" size="small" :icon="Edit" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="danger" size="small" :icon="Delete" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="pagination-section">
      <el-pagination
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑车位' : '新增车位'"
      width="520px"
      :close-on-click-modal="false"
    >
      <el-form ref="formRef" :model="parkingForm" :rules="rules" label-width="100px">
        <el-form-item label="车位编号" prop="numbers">
          <el-input v-model="parkingForm.numbers" placeholder="请输入车位编号" maxlength="25" />
        </el-form-item>
        <el-form-item label="车位状态" prop="status">
          <el-radio-group v-model="parkingForm.status">
            <el-radio :label="item.value" v-for="item in statusOptions" :key="item.value">
              {{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="关联业主">
          <el-select
            v-model="parkingForm.ownerId"
            placeholder="可选择关联业主"
            clearable
            filterable
            remote
            :remote-method="remoteSearchOwner"
            :loading="ownerLoading"
            style="width: 100%"
          >
            <el-option
              v-for="item in ownerOptions"
              :key="item.id"
              :label="ownerLabel(item)"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="parkingForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDialog">取消</el-button>
          <el-button type="primary" :loading="submitLoading" @click="submitForm(formRef)">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="css" scoped>
.parking-view {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
  box-sizing: border-box;
}

.page-header {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.08);
}

.page-header h2 {
  margin: 0 0 6px;
  color: #303133;
  font-size: 20px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #909399;
  font-size: 13px;
}

.search-section,
.action-section,
.table-section,
.pagination-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.04);
}

.search-section {
  margin-bottom: 16px;
}

.action-section {
  display: flex;
  gap: 12px;
  align-items: center;
  margin: 16px 0;
}

.table-section {
  margin-bottom: 16px;
}

.pagination-section {
  text-align: right;
}

.cell-sub {
  color: #909399;
  font-size: 12px;
}

.dialog-footer {
  text-align: right;
}
</style>
